<template>
  <div id="addPicturePage">
    <h2 style="margin-bottom: 16px; text-align: center">
      {{ route.query?.id ? '石头剪刀布' : '石头剪刀布' }}
    </h2>

    <!-- 左右布局容器 -->
    <div class="comparison-container">
      <!-- 左侧组件 -->
      <div class="comparison-item">
        <PictureUpload :picture="picture1" :onSuccess="onSuccess1" />
        <a-form v-if="picture1" layout="vertical" :model="pictureForm1" @finish="handleSubmit1">
          <a-form-item label="标签" name="tags">
            <a-select
              v-model:value="pictureForm1.tags"
              :options="tagOptions"
              mode="tags"
              placeholder="请输入标签"
              allowClear
            />
          </a-form-item>
        </a-form>
      </div>

      <!-- 中间VS按钮 -->
      <div class="vs-container">
        <div class="vs-button" @click="handleVsClick">VS</div>
      </div>

      <!-- 右侧组件 -->
      <div class="comparison-item">
        <PictureUpload :picture="picture2" :onSuccess="onSuccess2" />
        <a-form v-if="picture2" layout="vertical" :model="pictureForm2" @finish="handleSubmit2">
          <a-form-item label="标签" name="tags">
            <a-select
              v-model:value="pictureForm2.tags"
              :options="tagOptions"
              mode="tags"
              placeholder="请输入标签"
              allowClear
            />
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 脚本部分与之前保持一致，无需修改
import PictureUpload from '@/components/PictureUpload.vue'
import { ref } from 'vue'
import { reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { onMounted } from 'vue'
import { editPictureUsingPost } from '@/api/pictureController'
import { listPictureTagCategoryUsingGet } from '@/api/pictureController'
import { getPictureVoByIdUsingGet } from '@/api/pictureController'
import { Modal } from 'ant-design-vue'

const picture1 = ref<API.PictureVO>()
const pictureForm1 = reactive<API.PictureEditRequest>({})
const picture2 = ref<API.PictureVO>()
const pictureForm2 = reactive<API.PictureEditRequest>({})

const onSuccess1 = (newPicture: API.PictureVO) => {
  picture1.value = newPicture
  pictureForm1.name = newPicture.name
  pictureForm1.tags = newPicture.tags
}
const onSuccess2 = (newPicture: API.PictureVO) => {
  picture2.value = newPicture
  pictureForm2.name = newPicture.name
  pictureForm2.tags = newPicture.tags
}
const router = useRouter()

const handleSubmit1 = async (values: any) => {
  const pictureId = picture1.value?.id
  if (!pictureId) return
  const res = await editPictureUsingPost({ id: pictureId, ...values })
  if (res.data.code === 0) {
    message.success('操作成功')
    router.push({ path: `/picture/${pictureId}` })
  } else {
    message.error('操作失败：' + res.data.message)
  }
}

const handleSubmit2 = async (values: any) => {
  const pictureId = picture2.value?.id
  if (!pictureId) return
  const res = await editPictureUsingPost({ id: pictureId, ...values })
  if (res.data.code === 0) {
    message.success('操作成功')
    router.push({ path: `/picture/${pictureId}` })
  } else {
    message.error('操作失败：' + res.data.message)
  }
}

const handleVsClick = () => {
  // 检查图片是否都已上传
  if (!picture1.value || !picture2.value) {
    Modal.warning({
      title: '对比准备',
      content: '请先上传两张图片再进行对比',
      okText: '知道了',
    })
    return
  }

  // 检查标签是否填写
  if (!pictureForm1.tags || !pictureForm2.tags) {
    Modal.warning({
      title: '标签缺失',
      content: '请为两张图片都添加标签',
      okText: '去添加',
    })
    return
  }

  // 获取pictureForm2.tags的值
  const tags2 = pictureForm2.tags
  console.log('右侧玩家：', tags2)

  // 这里可以添加对比逻辑
  // 例如：比较两个图片的标签差异
  const compareResult = compareTags(pictureForm1.tags, tags2)

  // 显示对比结果
  Modal.info({
    title: '对战结果',
    content: `
    ${compareResult}
    `,
    okText: '关闭',
  })
}

// 标签对比函数
const compareTags = (tags1: string[], tags2: string[]) => {
  // 提取两个图片的标签（假设每个图片只有一个标签）
  const tag1 = tags1[0] || ''
  const tag2 = tags2[0] || ''

  // 检查标签是否有效
  if (!['石头', '剪刀', '布'].includes(tag1) || !['石头', '剪刀', '布'].includes(tag2)) {
    return '请使用"石头"、"剪刀"、"布"作为标签'
  }

  // 石头剪刀布胜负逻辑
  const resultMap = {
    '石头-剪刀': '左侧玩家（石头）获胜！',
    '剪刀-布': '左侧玩家（剪刀）获胜！',
    '布-石头': '左侧玩家（布）获胜！',
    '剪刀-石头': '右侧玩家（石头）获胜！',
    '布-剪刀': '右侧玩家（剪刀）获胜！',
    '石头-布': '右侧玩家（布）获胜！',
    相同: '平局！',
  }

  // 判断胜负
  let result = '未知结果'
  if (tag1 === tag2) {
    result = resultMap['相同']
  } else {
    const key = `${tag1}-${tag2}`
    result = resultMap[key] || '未知胜负关系'
  }

  return result
}
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])

const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    tagOptions.value = (res.data.data.tagList ?? []).map((data) => ({ value: data, label: data }))
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data) => ({
      value: data,
      label: data,
    }))
  } else {
    message.error('加载选项失败：' + res.data.message)
  }
}

const route = useRoute()

const getOldPicture1 = async () => {
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({ id: id })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture1.value = data
      pictureForm1.name = data.name
      pictureForm1.introduction = data.introduction
      pictureForm1.category = data.category
      pictureForm1.tags = data.tags
    }
  }
}

const getOldPicture2 = async () => {
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({ id: id })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture2.value = data
      pictureForm2.name = data.name
      pictureForm2.introduction = data.introduction
      pictureForm2.category = data.category
      pictureForm2.tags = data.tags
    }
  }
}

onMounted(() => {
  getOldPicture1()
  getOldPicture2()
  getTagCategoryOptions()
})
</script>

<style scoped>
/* 基础布局样式 */
#addPicturePage {
  max-width: 100%;
  padding: 20px;
}

.comparison-container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;
  gap: 20px;
  margin-top: 30px;
  flex-wrap: wrap; /* 小屏幕自动换行 */
}

.comparison-item {
  flex: 1;
  min-width: 300px; /* 最小宽度 */
  max-width: 45%; /* 最大宽度 */
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* VS按钮样式 */
.vs-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
  margin-top: 60px; /* 垂直居中 */
}

.vs-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: #f0f0f0;
  border-radius: 50%;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.vs-button:hover {
  transform: scale(1.1);
  background: #e0e0e0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .comparison-container {
    flex-direction: column;
    align-items: center;
  }

  .comparison-item {
    max-width: 100%;
    margin-bottom: 30px;
  }

  .vs-container {
    margin-top: -30px; /* 移动端调整位置 */
    order: 1; /* 调整显示顺序 */
  }
}

/* 图片上传组件样式 */
.picture-upload :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-height: 180px;
  min-width: 100%;
  margin-bottom: 15px;
}

.picture-upload img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.ant-upload-select-picture-card i {
  font-size: 40px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 10px;
  color: #666;
}
</style>
